package com.miracle9.game.service;

import com.miracle9.game.dao.PayLogServiceDao;
import com.miracle9.game.dao.BusineAccountsServiceDao;
import com.miracle9.game.dao.BusineServiceDao;
import com.miracle9.game.dao.BusineInfoServiceDao;
import com.miracle9.game.dao.BusineInfoTempServiceDao;
import com.miracle9.game.dao.SystemConfigServiceDao;
import com.miracle9.game.dao.UserAwardServiceDao;
import com.miracle9.game.dao.ComputerOrderServiceDao;
import com.miracle9.game.entity.Busine;
import com.miracle9.game.entity.BusineAccounts;
import com.miracle9.game.entity.BusineInfo;
import com.miracle9.game.entity.BusineLog;
import com.miracle9.game.entity.BusineLog.BusineType;
import com.miracle9.game.server.message.AmfMessageSend;
import com.miracle9.game.entity.SystemConfig;
import com.miracle9.game.util.MyUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("busineService")
public class BusineService
  extends BaseService
{
  @Autowired
  private BusineServiceDao busineServiceDao;
  @Autowired
  private SystemConfigServiceDao systemConfigServiceDao;
  @Autowired
  private BusineInfoServiceDao busineInfoServiceDao;
  @Autowired
  private PayLogServiceDao payLogServiceDao;
  @Autowired
  private UserAwardServiceDao userAwardServiceDao;
  @Autowired
  private ComputerOrderServiceDao computerOrderServiceDao;
  @Autowired
  private BusineAccountsServiceDao busineAccountsServiceDao;
  @Autowired
  private BusineInfoTempServiceDao busineInfoTempServiceDao;
  @Autowired
  private com.miracle9.game.dao.BusineLogServiceDao busineLogServiceDao;
  
  public Map<String, Object> busineInfo(IoSession session)
  {
    Map<String, Object> result = new HashMap();
    Busine busine = this.busineServiceDao.getAndSave();
    if (busine.getStatus() == 2)
    {
      result.put("busineStatus", Integer.valueOf(2));
      result.put("workType", Integer.valueOf(0));
      result.put("busineInfo", new BusineInfo[0]);
      return result;
    }
    List<BusineInfo> info = this.busineInfoServiceDao.q_CreateSqlList(
      "from BusineInfo where busineId = ? and currentShiftType=? and waiter=1", new Object[] { Integer.valueOf(busine.getId()), 
      Integer.valueOf(busine.getCurrentShiftType()) });
    for (BusineInfo i : info)
    {
      double revenue = i.getPayCount() - i.getExchangeCount() + i.getTakeDeposit() - i.getReturnDeposit();
      revenue = MyUtil.returnBigDecimalDoubleValue(revenue);
      i.setRevenue(revenue);
    }
    result.put("busineStatus", Integer.valueOf(busine.getStatus()));
    result.put("workType", Integer.valueOf(busine.getCurrentShiftType()));
    result.put("busineInfo", info.toArray(new BusineInfo[0]));
    return result;
  }
  
  public synchronized Map<String, Object> beginBusiness(IoSession session)
  {
    Map<String, Object> result = new HashMap();
    SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
    if (config.getSwitchType() == -1)
    {
      result.put("success", Boolean.valueOf(false));
      result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "notOpenJiaojie"));
      return result;
    }
    Busine busine = this.busineServiceDao.getAndSave();
    if (busine.getStatus() == 2)
    {
      Busine newBusine = new Busine();
      

      newBusine.setStartDate(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
      newBusine.setStatus(0);
      newBusine.setShiftWorkType(config.getSwitchType());
      if (config.getSwitchType() == 0) {
        newBusine.setCurrentShiftType(0);
      } else {
        newBusine.setCurrentShiftType(1);
      }
      this.busineServiceDao.save(newBusine);
      List<Object[]> busineTemps = this.busineInfoTempServiceDao.getAdminAndSum(newBusine.getStartDate());
      for (Object[] o : busineTemps)
      {
        BusineInfo info = new BusineInfo();
        info.setBusineId(newBusine.getId());
        info.setCurrentShiftType(newBusine.getCurrentShiftType());
        info.setStartTime(newBusine.getStartDate());
        info.setPayCount(Integer.parseInt(o[1].toString()));
        info.setExchangeCount(Double.parseDouble(o[2].toString()));
        info.setTakeDeposit(Integer.parseInt(o[3].toString()));
        info.setReturnDeposit(Integer.parseInt(o[4].toString()));
        info.setAdmin(o[0].toString());
        info.setWaiter(0);
        this.busineInfoServiceDao.save(info);
      }
    }
    else
    {
      busine.setStatus(0);
    }
    int adminId = Integer.valueOf(session.getAttribute("id").toString()).intValue();
    result.put("success", Boolean.valueOf(true));
    result.put("message", "");
    Map<String, Object> sysnMap = busineInfo(session);
    for (Integer id : com.miracle9.game.util.GameParameterAssist.be.keySet()) {
      if (id.intValue() != adminId) {
        AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity((IoSession)com.miracle9.game.util.GameParameterAssist.be.get(id), "busineInfo", new Object[] { sysnMap }));
      }
    }
    return result;
  }
  
  public Map<String, Object> pauseBusiness(IoSession session)
  {
    Map<String, Object> result = new HashMap();
    Busine busine = this.busineServiceDao.getAndSave();
    if (busine.getStatus() == 0)
    {
      busine.setStatus(1);
      this.busineServiceDao.update(busine);
    }
    int adminId = Integer.valueOf(session.getAttribute("id").toString()).intValue();
    result.put("success", Boolean.valueOf(true));
    result.put("message", "");
    Map<String, Object> sysnMap = busineInfo(session);
    for (Integer id : com.miracle9.game.util.GameParameterAssist.be.keySet()) {
      if (id.intValue() != adminId) {
        AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity((IoSession)com.miracle9.game.util.GameParameterAssist.be.get(id), "busineInfo", new Object[] { sysnMap }));
      }
    }
    return result;
  }
  
  public Map<String, Object> confirmHandOver(int infoId, IoSession session)
  {
    Map<String, Object> result = new HashMap();
    BusineInfo info = (BusineInfo)this.busineInfoServiceDao.getById(Integer.valueOf(infoId));
    if (info.getSettlementStatus() == 0)
    {
      result.put("success", Boolean.valueOf(false));
      result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "serverNotClosing"));
      return result;
    }
    info.setShiftWorkStatus(1);
    this.busineInfoServiceDao.update(info);
    result.put("success", Boolean.valueOf(true));
    result.put("message", "");
    return result;
  }
  
  public Map<String, Object> changeShifts(IoSession session)
  {
    Map<String, Object> result = new HashMap();
    Busine busine = this.busineServiceDao.getAndSave();
    if ((busine.getStatus() == 2) || (busine.getStatus() == 1))
    {
      result.put("success", Boolean.valueOf(false));
      result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "notOpenBusine"));
      return result;
    }
    int adminId = Integer.valueOf(session.getAttribute("id").toString()).intValue();
    this.busineInfoServiceDao.updateEndTime(MyUtil.dateFormatYMD_HMS_Sting(new Date()), busine.getId(), busine.getCurrentShiftType());
    if ((busine.getShiftWorkType() == 0) || ((busine.getShiftWorkType() == 1) && (busine.getCurrentShiftType() == 2)) || (
      (busine.getShiftWorkType() == 2) && (busine.getCurrentShiftType() == 3)))
    {
      stopBusine(busine);
    }
    else
    {
      busine.setStatus(0);
      busine.setCurrentShiftType(busine.getCurrentShiftType() + 1);
    }
    this.busineServiceDao.update(busine);
    result.put("success", Boolean.valueOf(true));
    result.put("message", "");
    Map<String, Object> sysnMap = busineInfo(session);
    for (Integer id : com.miracle9.game.util.GameParameterAssist.be.keySet()) {
      if (id.intValue() != adminId) {
        AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity((IoSession)com.miracle9.game.util.GameParameterAssist.be.get(id), "busineInfo", new Object[] { sysnMap }));
      }
    }
    return result;
  }
  
  public void stopBusine(Busine busine)
  {
    String startDate = busine.getStartDate();
    busine.setEndDate(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
    busine.setStatus(2);
    BusineAccounts account = new BusineAccounts();
    account.setStartDate(busine.getStartDate());
    account.setEndDate(busine.getEndDate());
    List<Object[]> logs = this.busineLogServiceDao.getList(startDate, account.getEndDate());
    int sumDeductGold = this.payLogServiceDao.getSumGoldByInterval(startDate, account.getEndDate());
    account.setDeductGold(sumDeductGold);
    for (Object[] o : logs)
    {
      int type = Integer.parseInt(o[0].toString());
      double money = Double.parseDouble(o[1].toString());
      if (type == BusineLog.BusineType.PAY.ordinal()) {
        account.setPayCount((int)money);
      } else if (type == BusineLog.BusineType.EXPIRY.ordinal()) {
        account.setExchangeCount(money);
      } else if (type == BusineLog.BusineType.LEASE.ordinal()) {
        account.setTakeDeposit((int)money);
      } else {
        account.setReturnDeposit((int)money);
      }
    }
    int giveGold = this.userAwardServiceDao.getSumGoldByInterval(startDate, account.getEndDate());
    account.setGiveGold(giveGold);
    double revenue = account.getPayCount() - account.getExchangeCount() + account.getTakeDeposit() - 
      account.getReturnDeposit();
    account.setRevenue(revenue);
    this.busineAccountsServiceDao.save(account);
  }
  
  public Map<String, Object> checkMoney(String money, IoSession session)
  {
    Map<String, Object> result = new HashMap();
    String username = session.getAttribute("username").toString();
    double checkMoney = Double.parseDouble(money);
    Busine busine = this.busineServiceDao.getAndSave();
    if ((busine.getStatus() == 2) || (busine.getStatus() == 1))
    {
      result.put("success", Boolean.valueOf(false));
      result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "notOpenBusine"));
      return result;
    }
    BusineInfo info = this.busineInfoServiceDao.getBusineInfo(username, busine.getId(), busine.getCurrentShiftType());
    if (info == null)
    {
      info = new BusineInfo();
      info.setBusineId(busine.getId());
      info.setStartTime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
      info.setCurrentShiftType(busine.getCurrentShiftType());
      info.setSettlementStatus(1);
      info.setSettlementMoney(checkMoney);
      info.setAdmin(username);
      info.setWaiter(1);
      this.busineInfoServiceDao.save(info);
    }
    else
    {
      if (info.getShiftWorkStatus() == 1)
      {
        result.put("success", Boolean.valueOf(false));
        result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "closingError"));
        return result;
      }
      info.setSettlementStatus(1);
      info.setSettlementMoney(checkMoney);
      this.busineInfoServiceDao.update(info);
    }
    result.put("success", Boolean.valueOf(true));
    result.put("message", "");
    return result;
  }
  
  public Object[] getMonthBusine(String date, IoSession session)
  {
    List<Object> result = new ArrayList();
    List<Object[]> busines = this.busineServiceDao.getListBydate(date);
    int i = 1;
    for (Object[] o : busines)
    {
      Map<String, Object> map = new HashMap();
      map.put("id", (Integer)o[0]);
      map.put("index", Integer.valueOf(i));
      int type = ((Integer)o[1]).intValue();
      if (type == 0) {
        map.put("type", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "notShift"));
      } else if (type == 1) {
        map.put("type", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "shiftAB"));
      } else if (type == 2) {
        map.put("type", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "shiftABC"));
      }
      map.put("income", o[2] == null ? Integer.valueOf(0) : o[2]);
      map.put("startTime", o[3]);
      map.put("endTime", o[4]);
      i++;
      result.add(map);
    }
    return result.toArray(new Object[0]);
  }
  
  public Object[] getBusineInfo(int busineId, int shiftType, IoSession session)
  {
    List<Object> result = new ArrayList();
    Busine busine = (Busine)this.busineServiceDao.getById(Integer.valueOf(busineId));
    String hql = "";
    if (busine.getShiftWorkType() != 0) {
      shiftType++;
    }
    hql = "from BusineInfo where busineId = ? and currentShiftType=" + shiftType;
    List<BusineInfo> busineInfos = this.busineInfoServiceDao.q_CreateSqlList(hql, new Object[] { Integer.valueOf(busineId) });
    for (BusineInfo b : busineInfos)
    {
      Map<String, Object> map = new HashMap();
      map.put("id", Integer.valueOf(b.getId()));
      map.put("operatorId", b.getAdmin());
      map.put("charge", Integer.valueOf(b.getPayCount()));
      map.put("gift", Double.valueOf(b.getExchangeCount()));
      map.put("borrow", Integer.valueOf(b.getTakeDeposit()));
      map.put("back", Integer.valueOf(b.getReturnDeposit()));
      
      double revenue = b.getPayCount() - b.getExchangeCount() + b.getTakeDeposit() - b.getReturnDeposit();
      revenue = MyUtil.returnBigDecimalDoubleValue(revenue);
      map.put("all", Double.valueOf(revenue));
      result.add(map);
    }
    return result.toArray(new Object[0]);
  }
  
  public Object[] getAdminBusineInfo(int busineInfoId, IoSession session)
  {
    List<Map<String, Object>> result = new ArrayList();
    BusineInfo info = (BusineInfo)this.busineInfoServiceDao.getById(Integer.valueOf(busineInfoId));
    List<BusineLog> busineLogs = this.busineLogServiceDao.q_CreateSqlList(
      "from BusineLog where admin=? and datetime>=? and datetime<? order by id", new Object[] { info.getAdmin(), 
      info.getStartTime(), info.getEndTime() });
    for (BusineLog p : busineLogs)
    {
      Map<String, Object> map = new HashMap();
      map.put("time", p.getDatetime());
      if (p.getType() == BusineLog.BusineType.PAY)
      {
        map.put("type", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "userPay"));
        map.put("gameCoin", Integer.valueOf(p.getGold()));
      }
      else if (p.getType() == BusineLog.BusineType.EXPIRY)
      {
        map.put("type", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "userExpiry"));
        map.put("gameCoin", Integer.valueOf(p.getGold()));
      }
      else if (p.getType() == BusineLog.BusineType.LEASE)
      {
        map.put("type", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "userZhujie"));
        map.put("gameCoin", "————");
      }
      else
      {
        map.put("type", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "userGuihai"));
        map.put("gameCoin", "————");
      }
      map.put("money", Double.valueOf(p.getMoney()));
      result.add(map);
    }
    return result.toArray(new Object[0]);
  }
}
